<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Book;

/**
 * BookSerach represents the model behind the search form about `app\models\Book`.
 */
class BookSerach extends Book
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'create_time'], 'integer'],
            [['title', 'author', 'socure','category'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Book::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'create_time' => $this->create_time,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'author', $this->author])
            ->andFilterWhere(['like', 'category', $this->category])
            ->andFilterWhere(['like', 'socure', $this->socure])->orderBy('create_time desc');

        return $dataProvider;
    }

    public function Z($ss)
    {
        //$ss='完美风暴';

        $URL='http://so.biquge.info/cse/search?q='. urlencode($ss).'&s=4403055038496925232&entry=1';
        $str=$this->vget($URL,'');
        $strZheng='/cpos="title".*?class="/si';
        $strZhengzz='/作者.*?<\/p>/si';
        preg_match_all ( $strZhengzz , $str , $array );//匹配出地址和内容
        $titlearray=array();
        foreach($array[0] as $ks=>$kv){
            $strkv='/<span>.*?<\/span>/si';
            preg_match ( $strkv , $kv , $arraytitle );
            $titlearray[]=strtr($arraytitle[0],['<span>'=>'','</span>'=>'']);
        }
        // echo $strZheng;
        preg_match_all ( $strZheng , $str , $array );//匹配出地址和内容

        $BOOK=new Book();
        // return $str;
        foreach($array[0] as $v=>$s){
            $strZheng1='/http:\/\/.*?\/"/si';
            preg_match ( $strZheng1 , $s , $array1 );//匹配出地址和内容
            $id=$this->generateuuid();
            $strZheng2='/title=".*?"/si';
            preg_match ( $strZheng2 , $s , $strZhengarr );//匹配出地址和内容
            $title=strtr($strZhengarr[0],['"'=>'','title='=>'']);
            if($BOOK::find()->where(['title'=>$title])->one()){

            }else{
                $BOOK::find()->createCommand()->insert(
                    'book',array('id'=>$id,
                        'title'=>$title,
                        'author'=>trim($titlearray[$v]),
                        'socure'=>substr($array1[0],0,-1),
                        'create_time'=>time())
                )->execute();
            }
        }
    }
    public function generateuuid()
    {
        // $this->Cai(substr($array1[0],0,-1),$id);
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = '';
        $hyphen = chr(45);
        $uuid = substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12);
        return $uuid;
    }
    function vget ( $url , $ucookie )
    { // 模拟登录获取Cookie函数

        $curl = curl_init (); // 启动一个CURL会话
        curl_setopt ( $curl , CURLOPT_URL , $url ); // 要访问的地址
        curl_setopt ( $curl , CURLOPT_SSL_VERIFYPEER , 0 ); // 对认证证书来源的检查
        curl_setopt ( $curl , CURLOPT_SSL_VERIFYHOST , 2 ); // 从证书中检查SSL加密算法是否存在
        curl_setopt ( $curl , CURLOPT_USERAGENT , $_SERVER['HTTP_USER_AGENT'] ); // 模拟用户使用的浏览器
        curl_setopt ( $curl , CURLOPT_FOLLOWLOCATION , 1 ); // 使用自动跳转
        curl_setopt ( $curl , CURLOPT_AUTOREFERER , 1 ); // 自动设置Referer
        curl_setopt ( $curl , CURLOPT_COOKIEJAR , $ucookie ); // 存放Cookie信息的文件名称
        curl_setopt ( $curl , CURLOPT_COOKIEFILE , $ucookie ); // 读取上面所储存的Cookie信息
        curl_setopt ( $curl , CURLOPT_TIMEOUT , 30 ); // 设置超时限制防止死循环
        curl_setopt ( $curl , CURLOPT_HEADER , 0 ); // 显示返回的Header区域内容
        curl_setopt ( $curl , CURLOPT_RETURNTRANSFER , 1 ); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec ( $curl ); // 执行操作
        if (curl_errno ( $curl )) {
            echo 'Errno' . curl_error ( $curl );
        }
        curl_close ( $curl ); // 关闭CURL会话
        return $tmpInfo; // 返回数据
    }
    public function zhua($url,$id)
    {
        $BookArticleModel= new BookArticle();
        //$url="http://www.biquge.info/22_22712/";
        $strIng=$this->vget($url,'');
//        $tt = '/\[{".*?"}\]/si';
        $strZheng='/<dd>.*?<\/dd>/si';
        preg_match_all ( $strZheng , $strIng , $array );//匹配出地址和内容
        foreach($array[0] as $s=>$k){
            preg_match('/[0-9]{4,}\w*\.html/si',$k,$arrayUrl); //撇配地址
            if(empty($arrayUrl)){
                echo '抓取完成';
            }
            $rt=json_encode($arrayUrl,true);
            $BookArticleModel::find()->createCommand()->insert('log',
                [
                    'log'=>iconv("gbk","UTF-8", $rt) ,
                    'log2'=>iconv("gbk","UTF-8", $k) ,
                    'create_time'=>time()
                ])->execute();
            //echo $rt;
            $urlTitle=$url.$arrayUrl[0];
            $strIngTitleContent=$this->vget($urlTitle,'');

            preg_match('/<h1>.*?<\/h1>/si',$strIngTitleContent,$arrayTitle); //匹配标题
            $title=strtr($arrayTitle[0],array('<h1>'=>'','</h1>'=>''));//去除多余
            preg_match('/id="content".*?<\/div>/si',$strIngTitleContent,$arrayTitleContent); //匹配标题
            $arrayContent=strtr($arrayTitleContent[0],array('&nbsp;'=>'','</div>'=>''));//去除多余
            $pattern = "/<.*>/";
            $pattern1="/id=.*? >/si";
            $content= preg_replace($pattern,"",$arrayContent);
            $content1= preg_replace($pattern1,"",$content);
            if($BookArticleModel::find()->where(['book_id'=>$id,'title'=>iconv("gbk","UTF-8", $title)])->one()){
            }else{

                $BookArticleModel::find()->createCommand()->insert('book_article',
                    [
                        'book_id'=>$id,
                        'title'=>iconv("gbk","UTF-8", $title) ,
                        'content'=>iconv( "gbk","UTF-8", $content1) ,
                        'url'=>$urlTitle,
                        'create_time'=>time()
                    ])->execute();
            }}
    }
}

